import { AfterViewInit, Component, OnDestroy, OnInit } from '@angular/core';
import { NzMessageService } from 'ng-zorro-antd';
import { BaseService, DataRegisterService, TemplateService, WorkflowService } from 'src/app/services';
import { EventManagerService } from 'src/app/services/event-manager.service';
import { OrganizationService } from 'src/app/services/organization.service';
import { UploadService } from 'src/app/services/upload.service';
import { BaseFieldComponent } from '..';
import { EngineService } from '../../../services/engine.service';
import { codeList, Workflow } from 'src/app/models';
import { PermitConfig, PermitConfigId } from '../../../models';
import { ExceptionHandler } from 'src/app/handler/exception.handler';

@Component({
    selector: 'zepride-search-bar',
    templateUrl: './search-bar.component.html',
    styleUrls: ['./search-bar.component.less', '../field.common.less']
})
export class SearchBarComponent extends BaseFieldComponent implements OnInit, AfterViewInit, OnDestroy {

    queryList = [];
    exQueryList = [];
    expand = false;
    addressOptions = codeList;
    addressData: any[];
    permitConfig: PermitConfig[] = [
        { mode: 'query', permitId: '查看', permitName: '', authObjectId: '' },
        { mode: 'edit', permitId: '编辑', permitName: '', authObjectId: '' },
        { mode: 'export', permitId: '导出', permitName: '', authObjectId: '' }
    ];
    searchable = true;
    editable = true;
    exportable = true;
    flowNodeNames = [];

    constructor(
        protected engineService: EngineService,
        protected baseSvr: BaseService,
        protected eventSvr: EventManagerService,
        protected orgSvr: OrganizationService,
        public uploadService: UploadService,
        protected msg: NzMessageService,
        protected dgSvr: DataRegisterService,
        private templateService: TemplateService,
        private workflowService: WorkflowService
    ) {
        super(engineService, baseSvr, eventSvr, orgSvr, uploadService, msg, dgSvr);
    }

    ngOnInit() {
        this.getDataSourceData();
        this.getWorkflowNodes();
    }

    ngAfterViewInit() {
        setTimeout(() => {
            const authData = this.setAuthorityData();
            this.zeprideAuthorityData = {
                ...authData,
                afterChecked: this.afterAuthChecked.bind(this)
            };
        }, 0);
    }

    async getDataSourceData() {
        const qList: any[] = this.componentData.extends.queryList;
        for (const item of qList) {
            if (item.ctrlType === 'select' && item.dsValue) {
                const dsId = item.dsValue[0];
                const ds = await this.dgSvr.getDataSourceById(dsId);
                if (ds.dataType.indexOf('keyValue') > -1) {
                    item.ds = ds.data;
                }
            }
        }
        this.queryList = qList.slice(0, 2);
        this.exQueryList = qList.slice(2, qList.length);
    }

    query() {
        if (this.componentData.extends.bindComTmpId) {
            this.emitEvent();
        }
    }

    addressChange(value: string[], item: { value: string; }) {
        value = value.filter(x => x !== '市本级' && x !== '省本级');
        item.value = value.join(',');
    }

    clean() {
        this.addressData = [];
        this.componentData.extends.queryList.forEach(n => {
            n.value = null;
            n.valueBegin = null;
            n.valueEnd = null;
        });
        this.emitEvent();
    }

    export() {
        if (!this.componentData.extends.bindComTmpId) {
            this.msg.error('未关联表格组件');
        }
        const searchParams = this.componentData.extends;
        this.eventSvr.tableDataExport(searchParams);
    }

    private emitEvent() {
        this.eventSvr.callEvents('search-bar.onQuery.' + this.componentData.extends.bindComTmpId, this.componentData.extends);
    }

    onChange(value: Date[], item: { valueBegin: Date; valueEnd: Date; }) {
        item.valueBegin = value[0];
        item.valueEnd = value[1];
    }

    afterAuthChecked(params: {
        permitId: PermitConfigId;
        isAuthorized: boolean;
    }) {
        if (!params.isAuthorized) {
            switch (params.permitId) {
                case '查看':
                    this.searchable = false;
                    break;
                case '导出':
                    this.exportable = false;
                    break;
                case '编辑':
                    this.editable = false;
                    break;
            }
        }
    }

    getTemplateItem(bindComTmpId: string) {
        return this.templateService.getTemplateItem(bindComTmpId);
    }

    getDataSourceById(dataSourceId: string) {
        return this.dataRegisterService.getDataSourceById(dataSourceId);
    }

    getWorkflowById(workflowId: string) {
        return this.workflowService.getWorkflowById(workflowId);
    }

    async getWorkflowNodes() {
        try {
            this.flowNodeNames = [];
            const templateItemId = this.componentData.extends.bindComTmpId;
            if (templateItemId) {
                const templateItem = await this.getTemplateItem(templateItemId);
                if (!templateItem.component.dataSource) {
                    return;
                }
                const dataSource = await this.getDataSourceById(templateItem.component.dataSource as string);
                const workflow = await this.getWorkflowById(dataSource.objectId);
                this.flowNodeNames = this.generateNodesByWorkflow(workflow);
            }
        } catch (error) {
            ExceptionHandler.current.handleError(error);
        }
    }

    generateNodesByWorkflow(workflow: Workflow) {
        const items = workflow.workflowNodeItems;
        items.sort((prev, next) => {
            const prevIndex = prev.flowNode.extends.index;
            const nextIndex = next.flowNode.extends.index;
            return prevIndex - nextIndex;
        });
        return items.map(item => item.flowNode.name);
    }

    ngOnDestroy() {
        if (this.modelChange$) {
            this.modelChange$.unsubscribe();
        }
    }

}
